import json

from PySide2.QtGui import QIcon, Qt
from PySide2.QtWidgets import QDialog
from qfluentwidgets import InfoBar, InfoBarPosition

from config import load_config
from interface.ui_dialog_advanced_config import Ui_Dialog

global win


class AdvancedConfigDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
        self.setFixedSize(525, 300)

        """self.ui.pushButton_config_save.setIcon(FluentIcon.SAVE)
        self.ui.pushButton_config_cancel.setIcon(FluentIcon.CANCEL)"""

        # self.ui.buttonBox.accepted.connect(self.on_save)
        self.ui.pushButton_config_save.clicked.connect(self.on_save)
        self.ui.pushButton_config_cancel.clicked.connect(self.close)

        # 加载默认配置
        self.config = self.loadConfig('config.json')

        self.ui.lineEdit_address.setText(self.config.get("address", ""))
        self.ui.lineEdit_channel.setText(self.config.get("channel", ""))

        self.ui.lineEdit_message_hour_1.setText(self.config.get("message_hour_1", ""))
        self.ui.lineEdit_message_hour_2.setText(self.config.get("message_hour_2", ""))
        self.ui.lineEdit_message_interval.setText(self.config.get("message_interval", ""))

        self.setWindowIcon(QIcon("assets/icon_setting.png"))
        self.setWindowTitle("配置")

    def loadConfig(self, filepath):
        """加载JSON配置文件"""
        try:
            with open(filepath, 'r') as json_file:
                return json.load(json_file)
        except FileNotFoundError:
            return {}


    def on_save(self):
        """保存配置到JSON文件"""
        if self.configure_check():
            pass
        else:
            return
        new_config = {
            "address": self.ui.lineEdit_address.text(),
            "channel": self.ui.lineEdit_channel.text(),
            "message_hour_1": self.ui.lineEdit_message_hour_1.text(),
            "message_hour_2": self.ui.lineEdit_message_hour_2.text(),
            "message_interval": self.ui.lineEdit_message_interval.text()
        }

        try:
            with open('config.json', 'r') as json_file:
                existing_config = json.load(json_file)
        except FileNotFoundError:
            existing_config = {}

        existing_config.update(new_config)

        with open('config.json', 'w') as json_file:
            json.dump(existing_config, json_file)

        load_config()
        self.close()
        win.configure_update_success()

    def configure_check(self):
        load_config()
        if not self.ui.lineEdit_address.text():
            InfoBar.warning(
                title='保存失败',
                content="配置项“链接服务器地址”未填写！",
                orient=Qt.Vertical,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=3000,
                parent=self,
            )
            return False
        if not self.ui.lineEdit_channel.text():
            InfoBar.warning(
                title='保存失败',
                content="配置项“渠道”未填写！",
                orient=Qt.Vertical,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=3000,
                parent=self,
            )
            return False
        if not self.ui.lineEdit_message_hour_1.text():
            InfoBar.warning(
                title='保存失败',
                content="配置项“调用主动消息时段”未填写全！",
                orient=Qt.Vertical,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=3000,
                parent=self,
            )
            return False
        if not self.ui.lineEdit_message_hour_2.text():
            InfoBar.warning(
                title='保存失败',
                content="配置项“调用主动消息时段”未填写全！",
                orient=Qt.Vertical,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=3000,
                parent=self,
            )
            return False
        if not self.ui.lineEdit_message_interval.text():
            InfoBar.warning(
                title='保存失败',
                content="配置项“调用主动消息间隔”未填写！",
                orient=Qt.Vertical,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=3000,
                parent=self,
            )
            return False
        return True
